package com.ds.robot.assistant.component;

import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 作用：这种方式解析JSON有点问题
 *
 * @author WeiShaoying
 *
 */
public class JsonFileReader2 {

    public static void main(String[] args) {
        String filePath = "demo/qx_userId.json";
        String content = readFileContent(filePath);
        // 解析 JSON 数据
        Map<String, Map<String, String>> dataMap = parseJson(content);
        ImmutableMap<String, String> immutableMap = buildImmutableMap(dataMap);
        immutableMap.forEach((name, userid) -> System.out.println(name + ": " + userid));
    }

    private static String readFileContent(String filePath) {
        StringBuilder content = new StringBuilder();
        try (InputStream inputStream = JsonFileReader.class.getClassLoader().getResourceAsStream(filePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);//.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }

    private static Map<String, Map<String, String>> parseJson(String content) {
        Gson gson = new Gson();
        return gson.fromJson(content, new TypeToken<Map<String, Map<String, String>>>() {
        }.getType());
    }

    private static ImmutableMap<String, String> buildImmutableMap(Map<String, Map<String, String>> dataMap) {
        ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
        dataMap.values().forEach(entry -> {
            String name = entry.get("name");
            String userid = entry.get("userid");
            builder.put(userid, name);
        });
        return builder.build();
    }
}
